package com.configurations;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.HttpMapperProperties;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

//Remove GSON HttpMessageConverter from Spring
//If another jar depends on GSON, but if GSON is present in the classpath Spring will use it instead of Jackson
//Since we want to use Jackson in Mu we need to disabled GSON capabilities in spring.
@Configuration
@ConditionalOnClass(HttpMessageConverter.class)
public class CustomHttpMessageConfig extends HttpMessageConvertersAutoConfiguration {

  @Autowired(required = false)
  private final List<HttpMessageConverter<?>> converters = Collections.emptyList();

  @Bean
  @ConditionalOnMissingBean
  public HttpMessageConverters messageConverters() {
    return new HttpMessageConverters(this.converters);
  }

  @Configuration
  @ConditionalOnClass(ObjectMapper.class)
  @ConditionalOnBean(ObjectMapper.class)
  @EnableConfigurationProperties(HttpMapperProperties.class)
  @SuppressWarnings("deprecation")
  protected static class MappingJackson2HttpMessageConverterConfiguration {

    @Autowired
    private HttpMapperProperties properties = new HttpMapperProperties();

    @Bean
    @ConditionalOnMissingBean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
      MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
      converter.setObjectMapper(objectMapper);
      if (this.properties.isJsonPrettyPrint() != null) {
        converter.setPrettyPrint(this.properties.isJsonPrettyPrint());
      }
      return converter;
    }

  }

}
